package com.easou.ps.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.easou.ps.thrift.qs.QSResult;
import com.easou.ps.thrift.search.mainsearch.MainSearchResponse;
import com.easou.ps.thrift.search.types.Result;
import com.easou.ps.webmaster.SearchRequest;
import com.easou.ps.webmaster.SearchResponse;
import com.easou.ps.webmaster.SearchResult;

public class ConvsUtils {
	
	public static SearchResponse convMainSearchResponse2SearchResponse(SearchRequest request, MainSearchResponse response,QSResult qsResult){
		SearchResponse result = new SearchResponse();
		result.setClickRerankLevel(response.getClickRerankLevel());
		result.setCorrectResult(qsResult.getCorrectResult());
		result.setDispNum(response.getDispNum());
		result.setRealNum(response.getResultsSize());
		result.setDebugInfo(new HashMap<String, String>());
		result.setResults(getResults(request, response));
		if(request.isDebug()){			
			result.putToDebugInfo("topInfo", response.getDebugInfo());
		}
		return result;
	}

	private static List<SearchResult> getResults(SearchRequest request, MainSearchResponse response) {
		List<SearchResult> results = new ArrayList<SearchResult>();
		List<Result> responseResults = response.getResults();
		for (int i = 0; i < responseResults.size(); i++) {
			SearchResult result = new SearchResult();
			result.setUrl(responseResults.get(i).getInfo().getUrl());
			result.setTitle(responseResults.get(i).getInfo().getTitle());
			
			// 问答整合传递dbsigns等信息
			if (result.getExtendFields() == null) {
				result.setExtendFields(new HashMap<String, String>());
			}
			
			// 时效性数据的摘要添加时间
			String summary = responseResults.get(i).getInfo().getSummary();
			result.setSummary(summary);
			
			result.setScore(responseResults.get(i).getHit().getScore());
			// 小时库需求
			
			
			Map<String, String> extendFields = responseResults.get(i).getExtendFields();
			String type = extendFields.get("type");
			if (type != null && !"".equals(type)) {
				result.setType(type);
			}
			String workerType = responseResults.get(i).getWorkerType()==null ? "" : responseResults.get(i).getWorkerType().name();
			result.putToExtendFields(FieldName.workerType, workerType);
			Map<String, String> map = result.getExtendFields();
			Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
			while (iterator.hasNext()) {
				Map.Entry<String, String> me = iterator.next();
				if (me.getValue() == null) {
					map.put(me.getKey(), "");
				}
			}
			if(request.isDebug()){	
				result.putToExtendFields("topInfo", responseResults.get(i).getExtendFields().get("topInfo"));
				result.putToExtendFields("bodyInfo", responseResults.get(i).getExtendFields().get("bodyInfo"));
			}
			results.add(result);
		}
		return results;
	}
}
